clear
use "$gendatadir/view_election.dta"

// Drop European Parliament elections
drop if election_type == "ep"

gen edate = date(election_date, "YMD")
format edate %td

// Calculate the election-to-election vote_share changes for each party before I merge in cabinets
// as these give multiple observations for parties in election periods.
sort country_name_short party_id edate
by   country_name_short party_id: gen vote_share_l1   = vote_share[_n-1]
by   country_name_short party_id: gen vote_share_d1   = vote_share       - vote_share[_n-1]
by   country_name_short party_id: gen vote_share_d1l1 = vote_share[_n-1] - vote_share[_n-2]
by   country_name_short party_id: gen vote_share_pcdiff = 100 * (vote_share - vote_share[_n-1])/vote_share[_n-1]

merge m:1 party_id using "$gendatadir/view_party.dta"
drop _merge

merge 1:m election_id party_id using "$gendatadir/view_cabinet.dta"
drop _merge

gen cdate = date(start_date, "YMD")
format cdate %td

sort country_name_short edate party_id cdate

replace caretaker = 0 if caretaker == .
replace prime_minister = 0 if prime_minister == .
replace cabinet_party = 0 if cabinet_party == .
drop if caretaker == 1

*drop if cabinet_party == 0
bysort cabinet_id: egen cab_leg_seats = total(seats) if cabinet_party == 1, missing
gen     minority_cab = 1 if cab_leg_seats / election_seats_total < 0.5
replace minority_cab = 0 if minority_cab == .

// Drop some unused variables
drop election_type start_date election_date party_name party_name_english left_right election_seats_total

sort election_id cdate
by election_id: egen min_cdate = min(cdate)
by election_id: egen max_cdate = max(cdate)
format min_cdate %td
format max_cdate %td
replace cdate = min_cdate if cdate == . 
drop if cdate != max_cdate

*sort party_id edate cdate
egen cabcount = group(country_name cdate)
sort party_id cabcount
tsset party_id cabcount

*by party_id: gen incumbent_pm = 1 if prime_minister[_n-1] == 1
by party_id: gen incumbent_pm = 1 if l.prime_minister == 1
replace incumbent_pm = 0 if incumbent_pm == .
gen pmfamid = family_id if incumbent_pm == 1
*by party_id: gen incumbent_minority = 1 if minority_cab[_n-1] == 1
by party_id: gen incumbent_minority = 1 if l.minority_cab == 1
replace incumbent_minority = 0 if incumbent_minority == .


gen year = year(edate)
replace year = year - 1 if halfyear(edate) == 1

drop if incumbent_pm != 1
rename vote_share pm_vote_share
rename vote_share_l1 pm_vote_share_l1
rename vote_share_d1 pm_vote_share_d1
rename vote_share_d1l1 pm_vote_share_d1l1
sort country_name_short year edate cdate
*by country_name_short year: drop if _n > 1
by country_name_short year: drop if _n != _N

save "$gendatadir/party_incumbent_voteshare.dta", replace

